import sys
import os
import shutil
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QFileDialog, QMessageBox
from PyQt5.QtGui import QPixmap
import re

class ImageMoveGUI(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Image Move")
        self.source_md_path = ""
        self.destination_path = ""
        self.image_preview_label = QLabel()  # 添加用于显示图片预览的Label
        layout = QVBoxLayout()

        # 添加选择源 Markdown 文件按钮
        self.source_button = QPushButton("选择源 Markdown 文件")
        self.source_button.clicked.connect(self.select_source_md)
        layout.addWidget(self.source_button)

        # 添加选择目标目录按钮
        self.destination_button = QPushButton("选择目标目录")
        self.destination_button.clicked.connect(self.select_destination_directory)
        layout.addWidget(self.destination_button)

        # 添加开始移动按钮
        self.move_button = QPushButton("开始移动")
        self.move_button.clicked.connect(self.move_images)
        layout.addWidget(self.move_button)

        # 显示选择的文件路径
        self.source_label = QLabel("源 Markdown 文件：")
        layout.addWidget(self.source_label)

        self.destination_label = QLabel("目标目录：")
        layout.addWidget(self.destination_label)

        layout.addWidget(self.image_preview_label)  # 将用于显示图片预览的Label添加到布局中

        self.setLayout(layout)

    def is_valid_path(self, path):
        print(path)
        try:
            return os.path.exists(path) and os.path.isfile(path)
        except OSError:
            return False

    def select_source_md(self):
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.ExistingFile)
        file_dialog.setNameFilter("Markdown文件 (*.md)")
        if file_dialog.exec_():
            self.source_md_path = file_dialog.selectedFiles()[0]
            print("Selected file:", self.source_md_path)
            self.source_label.setText(f"源 Markdown 文件：{self.source_md_path}")

        

    def select_destination_directory(self):
        self.destination_path = QFileDialog.getExistingDirectory(self, "选择目标目录")
        self.destination_label.setText(f"目标目录：{self.destination_path}")

    def move_images(self):
        if self.source_md_path == "" or self.destination_path == "":
            return

        # 提取 Markdown 文件中的图片路径
        image_paths = self.extract_image_paths(self.source_md_path)

        # 显示图片路径以及目标目录
        if image_paths:
            image_info = "提取到的图片路径：\n" + "\n".join(image_paths)
            self.image_preview_label.setText(image_info)
            self.destination_label.setText(f"目标目录：{self.destination_path}")
        
        print(image_paths)
        # 创建目标目录（如果不存在）
        os.makedirs(self.destination_path, exist_ok=True)

        # 移动图片
        for image_path in image_paths:
            image_file = os.path.basename(image_path)
            destination_file = os.path.join(self.destination_path, image_file)
            print("---------------------")
            print(image_path)
            print(image_file)
            print(destination_file)
            print(self.destination_path)
            # 判读目录是绝对路径还是相对路径
            print(image_path)
            if not self.is_valid_path(image_path):
                image_path = os.path.join(os.path.dirname(self.source_md_path), image_path)
            print(image_path)
            print("---------------------")

            try:
                shutil.move(image_path, destination_file)  # 使用shutil.move进行移动操作
            except Exception as e:
                print(f"移动图片失败: {str(e)}")
        
        QMessageBox.information(self, "移动完成", "图片移动完成！")  # 在窗口显示移动完成的提示信息


    def extract_image_paths(self, md_file):
        image_paths = []
        with open(md_file, "r", encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                if line.startswith("<img"):
                    start_pos = line.find('src="') + 5
                    end_pos = line.find('"', start_pos)
                    image_path = line[start_pos:end_pos]
                    image_paths.append(image_path)
                else:
                    # 使用正则表达式匹配 []() 形式的图片链接
                    pattern = r"\[(.*?)\]\((.*?)\)"
                    matches = re.findall(pattern, line)
                    for match in matches:
                        image_path = match[1]
                        image_paths.append(image_path)
        return image_paths
                
        return image_paths

if __name__ == "__main__":
    app = QApplication(sys.argv)
    gui = ImageMoveGUI()
    gui.show()
    sys.exit(app.exec_())